import axios from "axios";
import router from "@/router";

export default class Axios {
  instance;
  constructor(config) {
    this.instance = axios.create(config);
    this.interceptors();
  }

   async request(config) {
    return new Promise(async (resolve, reject) => {
      try {
        const response = await this.instance.request<D>(config);
        resolve(response.data);
      } catch (error) {
        reject(error);
      }
    }) 
  }

  interceptors() {
    this.interceptorsRequest();
    this.interceptorsResponse();
  }

   interceptorsRequest() {
    this.instance.interceptors.request.use(
      (config) => {
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
  }
  interceptorsResponse() {
    this.instance.interceptors.response.use(
      (response) => {
        return response;
      },
      (error) => {
        switch (error.response.status) {
          case 401:
            router.push({ name: "login" });
            break;
          case 422:
            break;
        }
        return Promise.reject(error);
      }
    );
  }
}
